package com.sunda.spmsuser.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsuser.entity.SpmsRole;
import com.sunda.spmsuser.entity.SpmsRolePermission;
import com.sunda.spmsuser.mapper.SpmsRoleMapper;
import com.sunda.spmsuser.mapper.SpmsRolePermissionMapper;
import com.sunda.spmsuser.service.ISpmsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2021-01-25
 */
@Service
public class SpmsRoleServiceImpl extends ServiceImpl<SpmsRoleMapper, SpmsRole> implements ISpmsRoleService {

    @Autowired
    SpmsRoleMapper spmsRoleMapper;

    @Autowired
    SpmsRolePermissionMapper spmsRolePermissionMapper;

    @Override
    public List<Map<String, Object>> getRoleById(String userId) {
        return spmsRoleMapper.getUserRoleById(userId);
    }

    @Override
    public List<Map<String, Object>> getRoleList() {
        return spmsRoleMapper.selectRoleList();
    }

    /**
     *      {
     * 			"roleCnName": "需求提报员",
     * 			"roleInfo": "需求提报员",
     * 			"roleId": "1001",
     * 			"updateUser": "999947",
     * 			"createUser": "999947",
     * 			"roleEnName": "Demand Requester",
     * 			"uuid": "161556d97ae44139ad21659c5fb98e00"
     *      }
     *       uuid 为主键，存在则更新，不存在则新建
     * @param doc
     * @return
     */
    @Override
    public ResponseResult createRole(JSONObject doc) {
        try {
            if (!doc.containsKey("roleId") || doc.getString("roleId") == null){
                return ResponseResult.error("参数错误");
            }
            if (!doc.containsKey("uuid") || doc.getString("uuid") == null){
                return ResponseResult.error("参数错误");
            }
            String uuid = doc.getString("uuid");
            SpmsRole spmsRole = new SpmsRole();
            spmsRole.setRoleId(doc.getString("roleId"));
            spmsRole.setRoleCnName(doc.getString("roleCnName"));
            spmsRole.setRoleEnName(doc.getString("roleEnName"));
            spmsRole.setRoleInfo(doc.getString("roleInfo"));
            spmsRole.setCreateUser(doc.getString("createUser"));
            spmsRole.setUpdateUser(doc.getString("updateUser"));
            /** uuid 为空则新建数据 */
            if (uuid.length() == 0){
                spmsRole.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                if (spmsRoleMapper.selectOne(new QueryWrapper<SpmsRole>().eq("ROLE_ID", spmsRole.getRoleId())) != null){
                    return ResponseResult.error("roleId已存在请重试");
                }
                spmsRoleMapper.insert(spmsRole);
                return ResponseResult.success();
            }
            /** uuid 存在则更新数据 */
            spmsRole.setUuid(uuid);
            spmsRoleMapper.update(spmsRole, new QueryWrapper<SpmsRole>().eq("UUID", uuid));
            return ResponseResult.success();
        }catch (Exception e){
            return ResponseResult.error();
        }
    }

    /**
     * {
     * 	"rolePermList": [{
     * 		"roleUuid": "38a089dbe2c44545ab1f101cedeec0dc",
     * 		"permissionId": ["10001", "10002", "10003", "10004", "10005"]
     *        }, {
     * 		"roleUuid": "ff60bd7e73294417ab68bda207e2b5b0",
     * 		"permissionId": ["10001", "10002", "10003", "10004"]
     *    }]
     * }
     * 先删除 roleUuid 对应的关系数据，再新建 角色-权限 关系数据
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult createRolePerms(JSONObject doc) {
        if (!doc.containsKey("rolePermList") || doc.getJSONArray("rolePermList").size() == 0){
            return ResponseResult.error("请求参数错误");
        }
        try{
            JSONArray array = doc.getJSONArray("rolePermList");
            for (int i = 0; i < array.size(); i++){
                JSONObject object = array.getJSONObject(i);
                String roleUuid = object.getString("roleUuid");
                JSONArray arr = object.getJSONArray("permissionId");
                /** 先删除 roleUuid 下所有权限信息 */
                spmsRolePermissionMapper.delete(new QueryWrapper<SpmsRolePermission>().eq("ROLE_UUID", roleUuid));
                if (arr.size() > 0){
                    /** 新建 角色权限 信息 */
                    for (int j = 0; j < arr.size(); j++){
                        SpmsRolePermission rolePermission = new SpmsRolePermission();
                        rolePermission.setUuid(UUID.randomUUID().toString().replaceAll("-","").toLowerCase());
                        rolePermission.setRoleUuid(roleUuid);
                        rolePermission.setPermissionId(arr.getString(j));
                        spmsRolePermissionMapper.insert(rolePermission);
                    }
                }
            }
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.error();
        }
    }
}
